package com.zyong.encryption.server.netty.handler;

import java.util.concurrent.TimeUnit;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import org.springframework.stereotype.Component;
import io.netty.handler.timeout.IdleStateHandler;
import com.zyong.encryption.server.config.NettyConfig;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import com.zyong.encryption.common.netty.NettyPipelineInit;
import org.springframework.beans.factory.annotation.Autowired;
import com.zyong.encryption.common.enums.SerializeProtocolEnum;

/**
 * NettyServerHandlerInitializer.
 * @author xiaoyu
 */
@Component
public class NettyServerHandlerInitializer extends ChannelInitializer<SocketChannel> {

    private final NettyConfig nettyConfig;

    private final NettyServerMessageHandler nettyServerMessageHandler;

    private SerializeProtocolEnum serializeProtocolEnum;

    private DefaultEventExecutorGroup servletExecutor;

    @Autowired
    public NettyServerHandlerInitializer(final NettyConfig nettyConfig,
                                         final NettyServerMessageHandler nettyServerMessageHandler) {
        this.nettyConfig = nettyConfig;
        this.nettyServerMessageHandler = nettyServerMessageHandler;
    }

    public void setServletExecutor(final DefaultEventExecutorGroup servletExecutor) {
        this.servletExecutor = servletExecutor;
    }

    public void setSerializeProtocolEnum(final SerializeProtocolEnum serializeProtocolEnum) {
        this.serializeProtocolEnum = serializeProtocolEnum;
    }

    @Override
    protected void initChannel(final SocketChannel ch) {
        final ChannelPipeline pipeline = ch.pipeline();
        NettyPipelineInit.serializePipeline(serializeProtocolEnum, pipeline);
        pipeline.addLast("timeout",
                new IdleStateHandler(nettyConfig.getHeartTime(), nettyConfig.getHeartTime(), nettyConfig.getHeartTime(), TimeUnit.SECONDS));
        pipeline.addLast(nettyServerMessageHandler);
    }
}
